from flask import Blueprint, render_template, request, jsonify, current_app, send_file
from app.models.image_processor import ImageProcessor
from app.models.quality_checker import QualityChecker
from app.models.process_config import ProcessConfig
from app.models.task_manager import TaskManager
import os
import json
from werkzeug.utils import secure_filename

main = Blueprint('main', __name__)
task_manager = TaskManager()

@main.route('/')
def index():
    return render_template('index.html')

@main.route('/select_directory', methods=['GET'])
def select_directory():
    """选择目录"""
    dir_type = request.args.get('type')
    if dir_type not in ['input', 'output']:
        return jsonify({'error': '无效的目录类型'}), 400
    
    try:
        # 这里应该调用系统的目录选择对话框
        # 由于Web限制，这里只是示例
        if dir_type == 'input':
            # 返回目录统计信息
            stats = get_directory_stats(current_app.config['UPLOAD_FOLDER'])
            return jsonify({
                'path': current_app.config['UPLOAD_FOLDER'],
                'stats': stats
            })
        else:
            return jsonify({
                'path': os.path.join(current_app.config['UPLOAD_FOLDER'], 'output')
            })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def get_directory_stats(directory):
    """获取目录统计信息"""
    total_size = 0
    file_count = 0
    
    for root, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(('.jpg', '.jpeg', '.png')):
                file_path = os.path.join(root, file)
                total_size += os.path.getsize(file_path)
                file_count += 1
    
    return {
        'total_files': file_count,
        'total_size': total_size,
        'average_size': total_size // file_count if file_count > 0 else 0
    }

@main.route('/create_task', methods=['POST'])
def create_task():
    """创建新任务"""
    try:
        data = request.get_json()
        input_dir = data.get('input_dir')
        output_dir = data.get('output_dir')
        
        if not input_dir or not output_dir:
            return jsonify({'error': '请提供输入和输出目录'}), 400
        
        if not os.path.exists(input_dir):
            return jsonify({'error': '输入目录不存在'}), 400
        
        # 使用默认配置创建任务
        config = ProcessConfig()
        task_id = task_manager.create_task(input_dir, output_dir, config)
        
        return jsonify({
            'message': '任务创建成功',
            'task_id': task_id
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@main.route('/tasks')
def get_tasks():
    """获取所有任务状态"""
    tasks = task_manager.get_all_tasks()
    return jsonify([{
        'task_id': task['task_id'],
        'status': task['status'],
        'progress': task['progress'],
        'total_files': task['total_files'],
        'processed_files': task['processed_files'],
        'duration': task['duration'],
        'error': task['error'],

        'results': {
            filename: {
                'status': result.status,
                'filter_reasons': [
                    {'code': r.code, 'message': r.message, 'details': r.details}
                    for r in result.filter_reasons
                ],
                'analysis': result.analysis,
                'processed_path': result.processed_path
            }
            for filename, result in task.results.items()
        }
    } for task in tasks])

@main.route('/task/<task_id>/results')
def get_task_results(task_id):
    """获取特定任务的结果"""
    task = task_manager.get_task(task_id)
    if not task:
        return jsonify({'error': '任务不存在'}), 404
    
    return jsonify({
        'task_id': task['task_id'],
        'status': task['status'],
        'results': {
            filename: {

                'status': result.status,
                'filter_reasons': [
                    {'code': r.code, 'message': r.message, 'details': r.details}
                    for r in result.filter_reasons
                ],
                'analysis': result.analysis,
                'processed_path': result.processed_path
            }
            for filename, result in task['results'].items()
        }
    })


@main.route('/config', methods=['GET', 'POST'])
def config():
    """配置管理"""
    if request.method == 'POST':
        try:
            data = request.form
            config = ProcessConfig()
            
            # 更新配置参数
            config.quality_threshold = float(data.get('quality_threshold', config.quality_threshold))
            config.face_ratio_min = float(data.get('face_ratio_min', config.face_ratio_min))
            config.face_ratio_max = float(data.get('face_ratio_max', config.face_ratio_max))
            config.yaw_range = (
                float(data.get('yaw_min', config.yaw_range[0])),
                float(data.get('yaw_max', config.yaw_range[1]))
            )
            config.pitch_range = (
                float(data.get('pitch_min', config.pitch_range[0])),
                float(data.get('pitch_max', config.pitch_range[1]))
            )
            config.blur_threshold = float(data.get('blur_threshold', config.blur_threshold))
            
            # 保存配置
            current_app.config['PROCESS_CONFIG'] = config
            return jsonify({'message': '配置已更新'})
        except Exception as e:
            return jsonify({'error': str(e)}), 400
    
    # 获取当前配置
    config = current_app.config.get('PROCESS_CONFIG', ProcessConfig())
    return render_template('config.html', config=config, param_info=ProcessConfig.get_param_info()) 